package com.itheima.controller.exception;

import com.itheima.entity.Result;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
@ControllerAdvice
public class ProjectExceptionAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(
            MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
       /* String errorMesssage = "Invalid Request:";

        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + ", ";
        }*/
        return new Result(false, bindingResult.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody   //设置返回对应类型，不是网页
    public Result doAccessDeniedException(AccessDeniedException e) {

        return new Result(false,"抱歉您没有该权限", null);
    }
    // JSON convert exception
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result handleHttpMessageNotReadableException(
            HttpMessageNotReadableException ex) {
        return new Result(false, "JSON convert exception");
    }
}
